<template>
    <div class="tradeModel">
        <!-- <img src="@/assets/dingdanjilu.png" class="orderhistory" alt="" v-if="isDark == 1" @click="orderhistory">
        <img src="@/assets/dingdanjilu1.png" class="orderhistory" alt="" v-if="isDark == 0" @click="orderhistory"> -->
        <div class="className" @click="openSelectClass">
            <img class="img" :src="getIco(symbol)" />
            <div>
                {{ symbol }}
            </div>

            <div>
                <img src="@/assets/zhuanhuan.png" class="icon" alt="" v-if="isDark == 1">
                <img src="@/assets/zhuanhuan1.png" class="icon" alt="" v-if="isDark == 0">
            </div>
        </div>
        <!-- 类选弹框 -->
        <van-popup v-model:show="selectClassShow" position="left" :style="{ width: '80%', height: '100%' }">
            <ClassModel @change="tapClassItem"></ClassModel>
        </van-popup>
        <!-- 详细信息 -->
        <div class="detail">
            <div class="left">
                <div class="gl font14 m_b_20"> {{ formatPrice(guessDetails.price) }}</div>
                <div :class="guessDetails.diff > 0 ? 'rise' : guessDetails.diff < 0 ? 'drop' : ''">
                    <div class=" font12 ">{{ formatPrice(guessDetails.diff) }}</div>
                    <div class="font12 m_l_10"
                        :class="guessDetails.diff > 0 ? 'riseJT' : guessDetails.diff < 0 ? 'dropJT' : ''">{{
                            formatPrice(guessDetails.change, 2)
                        }}%</div>
                </div>
            </div>
            <div class="right">
                <div class="w50">
                    <div class="font10 m_b_10">{{ $t('eszg') }}</div>
                    <div class="gl font12">{{ formatPrice(guessDetails.high) }}</div>
                </div>
                <div class="w50">
                    <div class="font10 m_b_10">{{ $t('eszd') }}</div>
                    <div class="gl font12">{{ formatPrice(guessDetails.low) }}</div>
                </div>
                <div class="w50">
                    <div class="font10 m_b_10">{{ $t('esjyl') }}</div>
                    <div class="gl font12">{{ formatPrice(guessDetails.open) }}</div>
                </div>
                <!-- <div class="w50">
                    <div class="font10 m_b_10">{{ $t('esjylusd') }}</div>
                    <div class="gl font12">15.15</div>
                </div> -->
            </div>
        </div>
        <!-- k表图  -->
        <div class="kbTable">
            <div v-for="(item, i) in timeList" :key="i" :class="activeTime == i ? 'min-active tab' : 'tab'"
                @click="tabTimeSelect(i, item)">{{ item }}</div>
        </div>
        <!-- <Echartsline></Echartsline> -->
        <div id="chart" style="width:100%;height:400px"></div>

        <div class="bet">
            <div class="tips">
                <span>{{ $t('yue') }}:<lable class="rise">{{ formatPrice(userData.usdtAmount || 0.0, 3) }}$</lable>
                </span>
                <span> {{ $t('yqlr') }}:<lable class="rise">{{ formatPrice(betForm.amount *
                    confingList[activeTime]?.rate, 3) }}$</lable></span>
            </div>
            <br>
            <div class="quick-select">
                <div class="btn" @click="betForm.amount += 10">10 $</div>
                <div class="btn" @click="betForm.amount += 50">50 $</div>
                <div class="btn" @click="betForm.amount += 100">100 $</div>
                <div class="btn" @click="betForm.amount += 500">500 $</div>
            </div>
            <br>
            <div class="step">
                <van-stepper style="width: 100%;" input-width="50%" button-size="30px" v-model.number="betForm.amount"
                    integer min="5" step="1" :auto-fixed="false" />

            </div>

            <div class="opertor">
                <div class="flexdBtn" v-if="!isTradeRest()">
                    <div class="kd" @click="bet(1)">
                        <img class="icon" src="../assets/shangshengqushi.png" alt="">
                        {{ $t('kd') }}
                    </div>
                    <div class="kk" @click="bet(2)">
                        <img class="icon" src="../assets/xiajiangqushi.png" alt="">
                        {{ $t('kk') }}
                    </div>
                </div>
            </div>

        </div>
        <!-- 我的交易团队交易按钮 -->
        <div class="tabSelect2">
            <div @click="tapSelect2(1)" :class="activeTab2 == 1 ? 'tab2 activeTab2' : 'tab2'">{{ $t('wdjy') }}
            </div>
            <div @click="tapSelect2(2)" :class="activeTab2 == 2 ? 'tab2 activeTab2' : 'tab2'">{{ $t('tdjy') }}
            </div>
        </div>

        <div class="scrollList" ref="scrollContainer">
            <div class="font12 m_b_10 syModel">
                <div>
                    <span class="m_r_10">{{ $t('s') }}</span>
                    <span v-if="guesstodyTJ && guesstodyTJ.length > 0" class="drop ">{{
                        formatPrice(guesstodyTJ[0].amount, 3) }}</span>
                    <span v-else>0</span>

                </div>
                <div>
                    <span class="m_r_10">{{ $t('y') }}</span>
                    <span v-if="guesstodyTJ && guesstodyTJ.length > 1" class="rise">{{
                        formatPrice(guesstodyTJ[1].amount, 3) }}</span>
                    <span v-else>0</span>
                </div>
            </div>
            <div class="item" v-for="(item, i) in data.recordsList" @click="openDetails(item)">
                <div class="left">
                    <div class="font12 gl m_b_10">{{ item.min }}{{ $t('divide') }}</div>
                    <div class="font10">{{ formatDate(item.createAt, 'MM/DD HH:mm:ss') }}</div>
                </div>
                <div class="center">
                    <div class="font12 gl m_b_10">{{ item.symbol }}</div>
                    <div class="font10">{{ item.settlementFlag == 1 ? $t('wjs') : $t('yjs') }}</div>
                </div>
                
                <div class="right" v-if="Number(item.closePrice) > 0">
                    <div class="font12 rise m_b_10" v-if="item.bonus > 0">{{ formatPrice(item.bonus, 2) }}</div>
                    <div class="font12 drop m_b_10" v-if="item.bonus == 0">{{ formatPrice(item.amount, 2) }}</div>
                    <div class="font10 gl">{{ item.riseFall == 1 ? $t('z') : $t('d') }}</div>
                    <div v-if="showDJS(item.closeAt)" class="font10">
                        <van-count-down style="color:var(--tradeGL)" :time="showDJS(item.closeAt)" />
                    </div>
                </div>
                <div class="right" v-else>
                    <div>--</div>
                    <div v-if="showDJS(item.closeAt)">
                        <van-count-down format=" mm : ss " @finish="finishDJS"
                            style="font-size: 10px;color:var(--tradeGL)" :time="showDJS(item.closeAt)" />
                    </div>
                </div>

            </div>
            <div class="noData" v-if="data.total == 0">{{ $t('nodata') }}</div>
        </div>


        <van-popup v-model:show="showDetails" round position="bottom" :style="{ height: '100%' }">
            <OrderDetail :detailsRow='OrderDetailRow' @goBlack="showDetails = false"></OrderDetail>
        </van-popup>
        <van-popup v-model:show="showGMpage" round position="bottom" :style="{ height: '70%' }">
            <GmPage @close="closeGMPage" :checked="checked" :showGMpageClass="showGMpageClass"
                :confingList="confingList" :guessDetails="guessDetails" @handle="handlegmcg"></GmPage>
        </van-popup>
        <Orderhistory v-if="showOrderhistory" @goBlack="closeOrderhistory"></Orderhistory>
        <Loading :show="showLoading"></Loading>
    </div>
</template>
<script setup>
import Orderhistory from './components/orderhistory.vue'
import OrderDetail from './trade/OrderDetail.vue'
import { init, dispose, registerFigure } from 'klinecharts'
import { useI18n } from 'vue-i18n'
import { ref, onMounted, reactive, onBeforeUnmount, onUnmounted } from 'vue'
import { Popup, Picker } from 'vant';
import ClassModel from './trade/classModel.vue'
import Echartsline from './trade/echartsline.vue'
import GmPage from './trade/GmPage.vue'
import { WebSocketURL } from "@/api/url";
import { guessconfig, guessteamrecords, guessrecords, ticker, guesstoday, guessteamtoday, kline, guessBet, userInfo } from '@/api/api'
import { formatDate, formatPrice, getIco, getSymbolDecimal, isTradeRest } from '@/api/kit';
import { userStore } from '@/stores/modules/user';
import { useRoute, useRouter } from 'vue-router';
import { showToast, Popover } from 'vant';
import i18n from '@/i18/index';

const isDark = ref(0)
const router = useRouter()
const { t } = useI18n()
const checked = ref(false)
const showDetails = ref(false)
const OrderDetailRow = ref()
const callMethods = ref()

const selectClassShow = ref(false)
const activeTime = ref(0)
const activeTab2 = ref(1)
const showGMpageClass = ref('')
const showPicker = ref(false)
const showGMpage = ref(false)
const showLoading = ref(false)
const scrollContainer = ref()
const confingList = ref({})
const guesstodyTJ = ref([])
const route = useRoute()
const showOrderhistory = ref()
const showProductsDetail = ref()
const symbol = ref(route.query.symbol || "XAUUSD")
const guessDetails = ref({ symbol: symbol })
console.log("route.query.symbol ", route.query.symbol)
const data = reactive({
    recordsList: [],
    total: 0
})
const prams = ref({
    page: 0,
    size: 10,
})

const betForm = ref({
    amount: 5,
})
const timeList = ref([])

const socket = ref(null)
const userData = ref({})
const chartsList = ref([])
const chart = ref()
onMounted(() => {
    getguessconfig()
    getticker()
    getUserInfo()
    console.log(Option)
    if (localStorage.getItem('isDark')) {
        isDark.value = localStorage.getItem('isDark')
    }

    getrecords()
    scrollContainer.value.addEventListener("scroll", handleScroll);
  
    creatSocket()
    createChart()
})
onBeforeUnmount(() => {
    dispose('chart')
    if (scrollContainer.value) {
        scrollContainer.value.removeEventListener("scroll", handleScroll);
    }
    if (socket.value) {
        socket.value.close();
    }
});

const getUserInfo = () => {
    userInfo().then(res => {
        console.log(res)
        if (res && res.user) {
            userData.value = res.user
        }
    })
}
function showDJS(time) {
    const currentDate = new Date();
    const dateFromTimestamp = new Date(time * 1000);
    const timeDiffInMilliseconds = dateFromTimestamp.getTime() - currentDate.getTime();
    if (timeDiffInMilliseconds > 0) {
        return timeDiffInMilliseconds
    }
    else if (timeDiffInMilliseconds == 0) {
        getrecords()
    }
    return false

}
function timestampToDate(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
const openDetails = (item) => {
    OrderDetailRow.value = item
    showDetails.value = true
}
const orderhistory = () => {
    showOrderhistory.value = true
}
const closeProductsDetail = () => {
    showProductsDetail.value = false
}
const closeOrderhistory = () => {
    showOrderhistory.value = false
}
const createChart = async () => {
    await getKline()
    chart.value = init('chart', {
        styles: {
            yAxis: { show: true, inside: true, axisLine: { show: false } }, separator: {
                size: 0,
            },
            xAxis: { show: false },
            grid: { show: false }, indicator: { tooltip: { text: { size: 9 } } }, candle: {
                tooltip: { showRule: "follow_cross", showType: 'rect', text: { size: 10 } },
                area: {},

            }
        }
    })

    chart.value.setPriceVolumePrecision(getSymbolDecimal(symbol.value))
    chart.value.createIndicator({ name: "MACD", calcParams: [5, 10, 30], precision: getSymbolDecimal(symbol.value) })
    chart.value.createIndicator({ name: "MA", visible: true, calcParams: [5, 10, 30], styles: { size: 1 } }, true, { id: 'candle_pane', axisOptions: { scrollZoomEnabled: true } })

}
const openSelectClass = () => {
    selectClassShow.value = true
}
const checkedMn = (e) => {
    console.log(checked.value)
    data.recordsList = []
    data.total = 0
    if (checked.value) {
        prams.value = {
            // isSim: 2,
            page: 0,
            size: 10,
            // settlementFlag: -1,
        }
    } else {
        prams.value = {
            // isSim: 1,
            page: 0,
            size: 10,
            // settlementFlag: -1,
        }
    }
    getrecords()
}
const finishDJS = () => {
    prams.value.page = 0
    data.recordsList = []
    getrecords()
    getUserInfo()
}
const tapSelect2 = (i) => {
    activeTab2.value = i
    data.recordsList = []
    getrecords()
}
const tabTimeSelect = (e, value) => {
    prams.value.min = value
    value += 'm'
    activeTime.value = e
    console.log(socket.value)
    if (socket.value) {
        socket.value.send(JSON.stringify({ action: `${guessDetails.value.symbol}_${value}` }))
    }
    getKline(value)

    getrecords()
}
const closeGMPage = () => {
    showGMpage.value = false
}
const handlegmcg = () => {
    prams.value.page = 0
    data.recordsList = []
    showGMpage.value = false
    getrecords()
    getUserInfo()

}

const bet = (riseFall) => {
    betForm.value.riseFall = riseFall;
    betForm.value.min = confingList.value[activeTime.value].min
    // if (!prams.min) {
    //     showToast(t('xzjszq'))
    //     return
    // }
    if (betForm.value.amount > userData.value.usdtAmount) {
        showToast(t('yebz'))
        return
    }
    if (betForm.value.amount < 5) {

        showToast(t('zdjye5'))
        return
    }
    if (betForm.value.amount >10000) {
        showToast(t('dbjysx'))
        return
        }
    betForm.value.amount = Number(betForm.value.amount)
    betForm.value.symbol = guessDetails.value.symbol
    console.log("bet betForm", betForm.value)
    guessBet(betForm.value).then(res => {
        if (res && res.code == 10000) {
            showToast(t('xdcg'))
            getUserInfo()
            getrecords()

        } else if (res && res.code == 20000) {
            showToast(res.i18NCode ? t(res.i18NCode) : res.message);
        }
        console.log(res)

    })
}

const tapshowGMpage = (e) => {

    showGMpage.value = true
    showGMpageClass.value = e
}
const getticker = (e) => { //初始获取一个展示
    if (e) {
        guessDetails.value = e
        symbol.value = e.symbol


    } else {
        ticker({ symbol: symbol.value }).then(res => {
            if (res) {
                guessDetails.value = res

            }
        })
    }

}

const getKline = (e) => {
    console.log("symbol", symbol.value)
    kline(symbol.value, e || "1m").then(res => {
        console.log(res)
        if (res && res.length > 0 && Array.isArray(res)) {

            res.forEach(element => {
                element.timestamp = element.startTime * 1000
                chartsList.value.push(element)

            });
            chart.value.applyNewData(chartsList.value)
        }
    })
}

const tapClassItem = (item) => { //选择商品 管理弹框
    if (socket.value) {
        socket.value.send(JSON.stringify({ action: 'unsubscribe', data: `${guessDetails.value.symbol}` }))
        socket.value.send(JSON.stringify({ action:   `${item.symbol}`+"_1m" }))
        // socket.value.close();
    }
    selectClassShow.value = false
    showLoading.value = true
    data.recordsList = []
    data.total = 0
    console.log("tapClassItem", item)
    guessDetails.value = item
    symbol.value = item.symbol

    chartsList.value = []
    dispose('chart')

    // creatSocket()
    createChart()
    getrecords()
    showLoading.value = false
}
const getguessconfig = () => {
    showLoading.value = true
    guessconfig().then(res => {//获取配置
        showLoading.value = false
        if (res && res.list && res.list.length > 0) {
            confingList.value = res.list
            confingList.value.forEach((e) => {
                timeList.value.push(e.min);
            })
        }

    })
}
const handleScroll = () => {
    if (
        scrollContainer.value.scrollHeight - scrollContainer.value.scrollTop ===
        scrollContainer.value.clientHeight
    ) {
        console.log("滚动条到底部了");
        if (data.total > data.recordsList.length) {
            prams.value.page += 1;
            getrecords();
        }
    }
};

const getrecords = () => {
    if (chart.value) {
        chart.value.removeOverlay("orderPriceLine")
    }
    prams.value.symbol = symbol.value
    prams.value.min = prams.value.min || 1
    // prams.value.isSim = checked.value ? 2 : 1

    if (activeTab2.value == 1) {//我的竞猜列表
        guessrecords(prams.value).then(res => {
            console.log(res)
            if (res && res.list && res.list.length > 0) {
                if (prams.value.page > 0) {
                    data.recordsList = [...data.recordsList, ...res.list]
                }
                data.recordsList = res.list
                data.total = res.total

                if (data.recordsList[0].settlementFlag == 1 && data.recordsList[0].closeAt>Math.floor(Date.now() / 1000)) {
                    chart.value.createOverlay({
                        name: "simpleTag",
                        id: "orderPriceLine",
                        lock: true,
                        points: [
                            { timestamp: data.recordsList[0].createAt * 1000, value: data.recordsList[0].openPrice },
                        ], styles: {
                            line: {
                                style: 'dashed',
                                dashedValue: [2, 2],
                                color: '#f00',
                                size: 2
                            },
                            //                         text:{
                            //                             style: 'fill',
                            //   color: '#FFFFFF',
                            //   size: 12,
                            //   family: 'Helvetica Neue',
                            //   weight: 'normal',
                            //   // 'solid' | 'dashed'
                            //   borderStyle: 'solid',
                            //   borderDashedValue: [2, 2],
                            //   borderSize: 0,
                            //   borderRadius: 2,
                            //   borderColor: '#1677FF',
                            //   paddingLeft: -100,
                            //   paddingRight: 0,
                            //   paddingTop: 10,
                            //   paddingBottom: 0,
                            //   backgroundColor: 'transparent'
                            //                         }
                        },
                        extendData: '下单价' + data.recordsList[0].openPrice.toFixed(getSymbolDecimal(symbol.value)),
                        onPressedMoveStart: (event) => {
                            return false;
                        }
                    }, "candle_pane")
                } else {
                    chart.value.removeOverlay("orderPriceLine")
                }
                if (data.recordsList[0].settlementFlag == 1 && data.recordsList[0].closeAt<=Math.floor(Date.now() / 1000)){
                     setTimeout(() => {
                         getrecords()
                    }, 1000);
                }
            }
        })
        guesstoday(prams.value).then(res => {
            if (res) {
                guesstodyTJ.value = res
            }
        })
    } else { //团队竞猜列表
        guessteamrecords(prams.value).then(res => {
            console.log(res)
            if (res && res.list && res.list.length > 0) {
                data.recordsList = [...data.recordsList, ...res.list]
                data.total = res.total
            }
        })
        prams.value.symbol = ""
        guessteamtoday(prams.value).then(res => {
            if (res) {
                guesstodyTJ.value = res
            }
        })
    }
}

const creatSocket = () => {
    if (!userStore().address) {
        return
    }
    socket.value = new WebSocket(WebSocketURL + `?id=${userStore().address}`);
    socket.value.addEventListener('open', (event) => {
        socket.value.send(JSON.stringify({ action: symbol.value + "_1m" }));
    });
    socket.value.addEventListener('message', (event) => {

        if (event.data) {
            let data = JSON.parse(event.data)
            if (data.Action == 'ticker') {
                guessDetails.value = data.Data
            } else {
                if (data.Data) {
                    let klineData = JSON.parse(data.Data)
                    // console.log("klineData", klineData)
                    klineData.timestamp = klineData.startTime * 1000
                    chart.value.updateData(klineData)
                }

            }

        }
    });
    socket.value.addEventListener('error', (error) => {
        console.log('WebSocket error:', error);
    });
    socket.value.addEventListener('close', (event) => {
        console.log('WebSocket connection closed');
        if (this.$router.)
        showToast(t('klinedisconnect'))
    });
}
</script>
<style scoped lang="less">
.bet {
    .tips {
        width: 100%;
        display: flex;
        justify-content: space-evenly;
        font-size: 12px;

    }

    .quick-select {
        display: flex;
        justify-content: space-around;
        color: var(--tradeGL);

        .btn {
            width: 20%;
            text-align: center;
            border: dotted 1px;
        }
    }

    .step {
        background: var(--homeCardBg);
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;

        .van-stepper__input {
            background: var(--homeCardBg);
        }
    }

    .opertor {



        display: flex;
        width: 100%;
        justify-content: end;
        align-items: center;

        .btn {
            width: 20px;
            padding: 10px;
            font-size: 20px;
            border: 0px;
        }

        .flexdBtn {
            display: flex;
            width: 100%;
            padding: 10px;
            box-sizing: border-box;
            justify-content: space-between;
            z-index: 999;

            .icon {
                width: 15px;
                height: 15px;
                margin-right: 5px;
            }

            .kd {
                font-size: 13px;
                line-height: 13px;
                color: #fff;
                width: 47%;
                text-align: center;
                padding: 10px 0;
                background-color: #5ac326;
                border-radius: 5px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .kk {
                font-size: 13px;
                line-height: 13px;
                color: #fff;
                width: 47%;
                text-align: center;
                padding: 10px 0;
                border-radius: 5px;
                background-color: #c54e39;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .reset {
                display: flex;
                justify-content: center;
                text-align: center;
                width: 100%;
                color: grey;
            }
        }
    }
}

.tradeModel {
    padding: 10px;
    overflow: auto;
    height: calc(100vh - 80px);

    .scrollList {
        height: calc(100vh - 40%);
        overflow: auto;
        padding-bottom: 70px;
    }

    .detail {
        display: flex;

        .left {
            width: 50%;
            flex: none;
        }

        .right {
            display: flex;
            flex-wrap: wrap;

            .w50 {
                width: 50%;
                margin-bottom: 10px;
            }
        }
    }

    .kbTable {
        display: flex;

        .tab {
            font-size: 12px;
            line-height: 12px;
            width: 20%;
            text-align: center;
        }

        .min-active {
            font-weight: bold;
            width: 100%;
            color: red;
        }
    }

    .item {
        display: flex;
        justify-content: space-between;
        background: var(--homeCardBg);
        margin: 15px 0;
        padding: 10px;

        .left {
            width: 30%;
            flex: none;
        }

        .center {
            width: 40%;
        }

        .right {
            width: 30%;
            text-align: end;
        }
    }
}

.className {
    color: var(--tradeGL);
    font-size: 13px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    text-align: center;
    align-content: center;
    justify-items: center;

    img {
        width: 30px;
        height: 30px;
    }

    .icon {
        width: 15px;
        height: 15px;
        margin-left: 10px;
    }

}

.zsmn {
    position: absolute;
    right: 0%;
}

.gl {
    color: var(--tradeGL);
}

.tabSelect2 {
    position: sticky;
    top: -10px;
    display: flex;
    padding-top: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e1e1e14a;
    margin-bottom: 10px;

    .tab2 {
        padding: 5px 15px 0;
        font-size: 14px;
        line-height: 14px;
    }

    .activeTab2 {
        color: var(--activeTabbarText);
        position: relative;
    }

    .activeTab2:after {
        content: '';
        position: absolute;
        width: 25px;
        border-radius: 5px;
        height: 3px;
        background: var(--activeAfterBg);
        bottom: -10px;
        left: 50%;
        transform: translate(-50%);
    }
}

.queryModel {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;

    .queryselect {
        width: 48%;
        padding: 10px;
        box-sizing: border-box;
        border: 1px solid var(--homeCardBg);
        background: var(--homeCardBg);
        border-radius: 5px;
        font-size: 13px;
        line-height: 13px;
    }

}



.orderhistory {
    top: 20px;
    transform: translate(0, -50%);
    right: 10px;
    width: 15px;
    height: 15px;
    position: absolute;

}

.syModel {
    display: flex;
    justify-content: space-around;
    background: var(--homeCardBg);
    padding: 10px 0;
    line-height: 12px;
    border-radius: 5px;
}

//    .van-picker{
//     background:var(--backgroud) !important ;
//     color: var(--textColor) !important;
//    }</style>